import json

from social.account.models import User
from social.feed.models import Post
from social.gift.models import Gift
from social.im.api import ZIMAPI
from social.search.models import EsUser
from social.user.models import AVCallSetting, UserLike
from social.user.serializers import AVCallSettingSerializer


def funa():
    users = User.objects.filter(avatar_auth=True)
    for x in users:
        EsUser.new_instance(x)


def funb():
    users = User.objects.all()
    for x in users:
        x.lat = 30.538429
        x.lng = 114.34966299999999
        x.save(update_fields=['lat', 'lng'])
        from social.search.models import EsUser
        EsUser.new_instance(x)


def func():
    users = User.objects.all()
    for x in users:
        setting, _ = AVCallSetting.objects.get_or_create(user=x)
        setting.call_enabled = True
        setting.call_price = 100
        setting.save()
        x.av_call_setting = json.dumps(AVCallSettingSerializer(setting).data)
        x.save(update_fields=['av_call_setting'])


def fund():
    us = User.objects.all()
    for x in us:
        if x.avatar and x.avatar.name and not x.photos:
            photos = str(json.dumps(list([x.avatar.name])))
            x.photos = photos
            x.save(update_fields=['photos'])


def fune():
    us = User.objects.all()

    def divide_chunks(l, n):
        for i in range(0, len(l), n):
            yield l[i:i + n]

    im_id_splits = divide_chunks(us, 100)
    for u in im_id_splits:
        users = []
        for x in u:
            avatar = x.avatar.url if x.avatar else ''
            users.append(
                {'UserId': x.im_id, 'UserName': x.nickname, 'UserAvatar': avatar}
            )
        ZIMAPI().create_user(users)


def create_system_user():
    user = User.objects.get(phone='130')
    users = []
    users.append(
        {'UserId': user.im_id, 'UserName': user.nickname, 'UserAvatar': user.avatar.url}
    )
    ZIMAPI().create_user(users)


def test_like():
    from_user = User.objects.get(uid=200770)
    us = User.objects.order_by('-created_at')[:30]
    for x in us:
        UserLike.follow(from_user, x)


def test_visitor():
    from_user = User.objects.get(uid=200770)
    us = User.objects.order_by('-created_at')[:30]
    for x in us:
        if x.id != from_user.id:
            user_visit(x.id, from_user.id)


def test_post_like():
    post = Post.objects.first()
    u = User.objects.first()
    post.like(u)


def test_send_gift():
    u = User.objects.get(uid=200770)
    to_user = User.objects.first()
    gift = Gift.objects.first()
    gift.send(u, to_user)


